package com.zhu.transaction.controller;


import com.google.gson.Gson;
import com.sun.xml.internal.ws.resources.HttpserverMessages;
import com.zhu.transaction.mapper.UserMapper;
import com.zhu.transaction.mapper.imp.UserMapperImp;
import com.zhu.transaction.pojo.*;
import com.zhu.transaction.pojo.state.BackState;
import com.zhu.transaction.pojo.state.R;
import com.zhu.transaction.service.CategoryService;
import com.zhu.transaction.service.ProductService;
import com.zhu.transaction.service.UserService;
import com.zhu.transaction.utils.MyUtils;
import com.zhu.transaction.utils.UploadImgUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhu
 * @since 2021-01-07
 */
@Controller
@RequestMapping("/product")
@Api(tags = "商品管理接口", description = "商品的增删改查")
public class ProductController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    ProductService productService;

    @Autowired
    UserService userService;

    @RequestMapping("/release")
    @ApiOperation(value = "发布商品页面", hidden = true)
    public String releasePage(@RequestParam(value = "productId", required = false) String productId, Model model) {
        model.addAttribute("categories", categoryService.getAllCategory());
        //productId值不为空，代表着是更新商品信息
        if (productId != null) {
            Product productDetail = productService.getProductDetail(productId);
            productDetail.setMyCategory(categoryService.getCategoryById(productDetail.getCategory()));
            model.addAttribute("product", productDetail);
        }
        return "/main/release";
    }

    @ResponseBody
    @GetMapping("/second")
    @ApiOperation(value = "获取二级分类")
    public R getSecondCategory(@RequestParam String id) {
        return R.ok().data("data", categoryService.getSecondCategory(id));
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加商品", hidden = true)
    public String releaseProduct(Product product, HttpSession session) {
        User user = (User) session.getAttribute("user");
        product.setReleaseUser(user.getId());
        int result = productService.addProduct(product);
        R r = result > 0 ? R.ok().message("发布成功") : R.error().message("发布失败");
        session.setAttribute("backMessage", r);
        return "redirect:/product/release";
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新商品", hidden = true)
    public String updateProduct(Product product, HttpSession session) {
        BackState backState = productService.updateProduct(product);
        R r = backState == BackState.SUCCESS ? R.ok().message("更新成功") : R.error().message("更新失败");
        if (backState == BackState.NO_EXIST)
            r = R.error().message("该商品已不存在");
        session.setAttribute("backMessage", r);
        return "redirect:/product/release";
    }

    @GetMapping("/delete")
    @ApiOperation(value = "删除商品", hidden = true)
    public String deleteProduct(String productId, Boolean isLogic, HttpSession session) {
        BackState backState = productService.deleteProduct(productId, isLogic);
        if (backState == BackState.SUCCESS) {
            session.setAttribute("backMessage", new Gson().toJson(R.ok().message("删除成功")));
        } else {
            session.setAttribute("backMessage", new Gson().toJson(R.error().message("删除失败")));
        }
        return "redirect:/person/myRelease?curPage=1";
    }

    @RequestMapping("/list")
    @ApiOperation(value = "首页", hidden = true)
    public String getPageProduct(@RequestParam(value = "condition", required = false) String param,
                                 @RequestParam(value = "isDisPlayNav", required = false) Boolean isDisplay, Model model) {
        if (isDisplay == null) {
            isDisplay = true;
        }
        ProductCondition productCondition = new ProductCondition();
        if (param != null) {
            try {
                param = URLDecoder.decode(param, "UTF-8");
                productCondition = new Gson().fromJson(param, ProductCondition.class);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        //通过筛选条件获取一页的商品记录
        List<Product> productByPage = productService.getProductByPage(productCondition, 16);
        model.addAttribute("products", productByPage);
        model.addAttribute("productCondition", productCondition);

        //不是ajax请求，获取所用的分类信息
        if (!productCondition.getAjaxQuest()) {
            List<BackCategory> allCategory = categoryService.getAllCategory();
            BackCategory tmp = new BackCategory();
            tmp.setTitle("全部").setId("0");
            allCategory.add(0, tmp);
            model.addAttribute("categories", allCategory);
        }

        //获取当前的点击的分类信息
        Category clickCategory = categoryService.getCategoryById(productCondition.getCategoryId());
        clickCategory.setParentPojo(categoryService.getCategoryById(clickCategory.getParent()));
        model.addAttribute("curPage", productCondition.getCurPage());
        model.addAttribute("clickCategory", clickCategory);
        model.addAttribute("isDisplay", isDisplay);
        model.addAttribute("products_num", productService.getProductNum("0", productCondition));
        return productCondition.getAjaxQuest() ? "common/productList" : "main/main";
    }


    @GetMapping("/detail")
    @ApiOperation(value = "获取商品详情", hidden = true)
    public String getProductDetail(String category, String productId, Model model) {
        List<BackCategory> allCategory = categoryService.getAllCategory();
        BackCategory tmp = new BackCategory();
        tmp.setTitle("全部").setId("0");
        allCategory.add(0, tmp);
        model.addAttribute("categories", allCategory);

        Product product = productService.getProductDetail(productId);
        if (product == null || !product.getShelves()) {
            model.addAttribute("message", "该商品中已被卖家下架或删除！");
            return "/common/error";
        }
        product.setReleaseUserPojo(userService.getOneUserById(product.getReleaseUser()));
        model.addAttribute("clickCategory", categoryService.getCategoryById(category));
        model.addAttribute("product", product);
        return "/main/detail";
    }

    @ResponseBody
    @PostMapping("/shelves")
    @ApiOperation(value = "更新商品上架状态")
    public R updateProductShelves(String productId) {
        BackState backState = productService.updateProductShelves(productId);
        return backState == BackState.SUCCESS ? R.ok() : R.error();
    }

    @ResponseBody
    @PostMapping("/uploadProductImg")
    @ApiOperation(value = "上传商品图片")
    public R uploadImg(MultipartFile file) {
        String url = UploadImgUtils.uploadImg(file, "products", MyUtils.getRandomID());
        return R.ok().data("imgUrl", url);
    }

}
